﻿using System;
using System.Collections.Generic;
using System.IO;
using BitBenderGames;
using LogSystem;
using UnityEditor;
using UnityEngine;
using Yoozoo.UI.YGUI;
using Random = UnityEngine.Random;

namespace Yoozoo.Gameplay.City
{

    [Serializable]
    public class SubFogEditorConfig
    {
        public int fogId;
        public Color color = Color.red;
    }

    public class FogEditor : MonoBehaviour
    {
        private static string fogJsonPath = "Assets/ResourcesAssets/City/Config/fogJsonConfig.json";
        
        public int width = 200;
        public int height = 200;
        public float fogSize = 10;

        public float fogPosY = 5;

        public float fogOffsetX = -50;
        public float fogOffsetZ = -50;
        
        
        [Range(100,5000)]
        public float maxCameraHeight = 1000;
        
        [HideInInspector]
        public List<SubFogEditorConfig> subFogConfigs;

        private Dictionary<int, SubFogEditorConfig> subFogConfigMap;
        // 当前正在编辑的迷雾id
        public int currentFogId;

        public MeshRenderer fogRenderer;

        public Transform hudRoot;
        public GameObject hudObject;
        
        
        private bool editing = false;
        private float originMaxCameraHeight = 100;
        // 开始编辑
        public void Begin()
        {
            if (editing)
            {
                return;
            }
            
            if (fogRenderer == null)
            {
                Debug.LogError(LogModule.CitySimulation,"没有显示对象");
                return;
            }
            editing = true;

            Show();
            // 屏蔽TouchManager
            CityManager.Instance.CityTouchManager.UnRegister();
            CityManager.Instance.mobileTouchCamera.TouchInputController.OnDragUpdate += OnDragUpdate;
            CityManager.Instance.mobileTouchCamera.TouchInputController.OnDragStart += OnDragStart;
            CityManager.Instance.mobileTouchCamera.TouchInputController.OnDragStop += OnDragStop;
            // 摄像机参数修改
            originMaxCameraHeight = CityManager.Instance.mobileTouchCamera.CamZoomMax;
            CityManager.Instance.touchCameraController.LOD5 = maxCameraHeight;
            CityManager.Instance.touchCameraController.ZoomDistanceMax = maxCameraHeight;
            CityManager.Instance.mobileTouchCamera.CamZoomMax = maxCameraHeight;
            CityManager.Instance.touchCameraController.CameraGlobalValue.ZoomDistanceMax = maxCameraHeight;
            CityManager.Instance.touchCameraController.CameraGlobalValue.LODHeights[6] = maxCameraHeight;
            CityManager.Instance.mobileTouchCamera.Cam.farClipPlane = 10000;
            CityManager.Instance.touchCameraController.SetCameraBoundary(new Rect(-1000,-1000,2000,2000));

            CameraMoveComponent moveComponent = CityManager.Instance.mobileTouchCamera.transform.GetComponentInChildren<CameraMoveComponent>();
            moveComponent.ZoomTo(300,0.3f);
            // 关闭房间碰撞
            GameObject.Find("DataRoot").SetActive(false);
            
            
        }

        private int[,] fogIdArray;
        private Texture2D fogTexture;
        public void Show()
        {
#if UNITY_EDITOR
            subFogConfigMap = new Dictionary<int, SubFogEditorConfig>();
            foreach (var subFogConfig in subFogConfigs)
            {
                subFogConfigMap[subFogConfig.fogId] = subFogConfig;
            }
            
            fogRenderer.transform.position = new Vector3((width * fogSize/2.0f) + fogOffsetX,
                fogPosY,
                (height * fogSize/2.0f) + fogOffsetZ);
            fogRenderer.transform.localScale = new Vector3(width * fogSize / 10.0f,
                1,
                height * fogSize / 10.0f);
            
            // 根据配置显示迷雾
            fogIdArray = new int[width,height];
            if (File.Exists(fogJsonPath))
            {
                var fogText = AssetDatabase.LoadAssetAtPath<TextAsset>(fogJsonPath).text;
                CityFogConfig fogConfig = JsonUtility.FromJson<CityFogConfig>(fogText);
                // 长宽一样
                if (fogConfig.width == width && fogConfig.height == height)
                {
                    if (fogConfig.CitySubFogs!=null)
                    {
                        foreach (var citySubFog in fogConfig.CitySubFogs)
                        {
                            if (citySubFog.grids!=null)
                            {
                                foreach (var grid in citySubFog.grids)
                                {
                                    if (subFogConfigMap.ContainsKey(citySubFog.fogId))
                                    {
                                        fogIdArray[grid.x, grid.y] = citySubFog.fogId;
                                    }
                                }
                            }
                        }   
                    }
                }
            }
            
            // 根据迷雾数字写入像素
            fogTexture = new Texture2D(width, height, TextureFormat.RGBAFloat, false,false);
            fogTexture.filterMode = 0;
            
            for (int i = 0; i < fogIdArray.GetLength(0); i++)
            {
                for (int j = 0; j < fogIdArray.GetLength(1); j++)
                {
                    int fogId = fogIdArray[i, j];
                    if (fogId!=0 && subFogConfigMap.ContainsKey(fogId))
                    {
                        fogTexture.SetPixel(i, j, subFogConfigMap[fogId].color);
                    }
                    else
                    {
                        //fogTexture.SetPixel(i, j, new Color(1,Random.Range(0f,1f),Random.Range(0f,1f),1));       
                        fogTexture.SetPixel(i, j, new Color(0,0,0,0));       
                    }
                }
            }
            fogTexture.Apply();
            fogRenderer.sharedMaterial.SetTexture("_UVTex",fogTexture);

            ShowFogId(); 
#endif
           
        }


        public void UnShow()
        {
            fogRenderer.transform.localScale = Vector3.zero;
            
            HideFogId();
        }


        public void ShowFogId()
        {
#if UNITY_EDITOR

            HideFogId();
            
            if (File.Exists(fogJsonPath))
            {
                var fogText = AssetDatabase.LoadAssetAtPath<TextAsset>(fogJsonPath).text;
                CityFogConfig fogConfig = JsonUtility.FromJson<CityFogConfig>(fogText);
                // 长宽一样
                if (fogConfig.width == width && fogConfig.height == height)
                {
                    if (fogConfig.CitySubFogs!=null)
                    {
                        foreach (var citySubFog in fogConfig.CitySubFogs)
                        {
                            if (citySubFog.grids!=null && citySubFog.grids.Count > 0)
                            {
                                Vector2 t = Vector2.zero;
                                
                                foreach (var grid in citySubFog.grids)
                                {
                                    t += grid;
                                }

                                t /= (citySubFog.grids.Count * 1.0f);

                                Vector3 hudPos = new Vector3(t.x * fogSize + fogOffsetX + fogSize * 0.5f, 
                                    fogPosY + 0.1f,
                                    t.y * fogSize + fogOffsetZ + fogSize * 0.5f);

                                var hud = GameObject.Instantiate(hudObject, hudRoot);
                                hud.transform.position = hudPos;
                                hud.SetActive(true);
                                hud.GetComponentInChildren<YText>().text = citySubFog.fogId.ToString();
                            }
                        }   
                    }
                }
            }
#endif
        }

        public void HideFogId()
        {
            if (hudRoot.childCount > 0)
            {
                for (int i = hudRoot.childCount - 1; i >= 0; i--)
                {
                    GameObject.DestroyImmediate(hudRoot.GetChild(i).gameObject);
                }
            }
        }
        
        
        // 结束编辑
        public void End()
        {
            editing = false;
            CityManager.Instance.CityTouchManager.Register();
            CityManager.Instance.mobileTouchCamera.CamZoomMax = originMaxCameraHeight;
            CityManager.Instance.mobileTouchCamera.TouchInputController.OnDragUpdate -= OnDragUpdate;
            CityManager.Instance.mobileTouchCamera.TouchInputController.OnDragStart -= OnDragStart;
            CityManager.Instance.mobileTouchCamera.TouchInputController.OnDragStop -= OnDragStop;
        }


        private void Update()
        {
            if (Input.GetMouseButton(1))
            {
                if (!editing)
                {
                    return;
                }
                
                Vector3 hitPos;
                if (GetClickPos(Input.mousePosition,out hitPos))
                {
                    Vector2Int grid = GetGridFromPos(hitPos);
                    if (lastGrid.x == grid.x && lastGrid.y == grid.y) 
                    {
                        return;
                    }

                    if (grid.x < 0 || grid.x >= width || grid.y < 0 || grid.y >= height) 
                    {
                        return;
                    }
                    
                    lastGrid = grid;
                    WritePixel(grid);
                    fogTexture.Apply();
                    //fogRenderer.material.SetTexture("_UVTex",fogTexture);
                }
            }

            if (Input.GetMouseButton(2))
            {
                if (!editing)
                {
                    return;
                }
                
                Vector3 hitPos;
                if (GetClickPos(Input.mousePosition,out hitPos))
                {
                    Vector2Int grid = GetGridFromPos(hitPos);
                    if (lastGrid.x == grid.x && lastGrid.y == grid.y) 
                    {
                        return;
                    }
                    
                    if (grid.x < 0 || grid.x >= width || grid.y < 0 || grid.y >= height) 
                    {
                        return;
                    }
                    
                    lastGrid = grid;
                    fogTexture.SetPixel(grid.x, grid.y, new Color(0,0,0,0));
                    // 写入数据中
                    fogIdArray[grid.x, grid.y] = 0;
                    fogTexture.Apply();
                }
            }
        }

        private Vector2Int lastGrid = new Vector2Int(-1,-1);
        private void OnDragStart(Vector3 pos, bool islongtap, bool isonui)
        {
           
        }
        
        private void OnDragUpdate(Vector3 dragposstart, Vector3 dragposcurrent, Vector3 correctionoffset, bool isOnUI)
        {
            
        }
        
        private void OnDragStop(Vector3 dragstoppos, Vector3 dragfinalmomentum)
        {
               
        }
        
        private bool GetClickPos(Vector3 pos,out Vector3 hitPos)
        {
            Ray camRay = CityManager.Instance.mobileTouchCamera.Cam.ScreenPointToRay(pos);
            RaycastHit hit;
            if (Physics.Raycast(camRay, out hit,10000,1<<LayerMask.NameToLayer("FogCollision")))
            {
                hitPos = hit.point;
                return true;
            }
            hitPos = Vector3.back;
            return false;
        }

        private Vector2Int GetGridFromPos(Vector3 pos)
        {
            float xp = pos.x - fogOffsetX;
            float zp = pos.z - fogOffsetZ;
            
            return new Vector2Int(  (int)(xp/fogSize), (int)(zp/fogSize));
        }

        private void WritePixel(Vector2Int grid)
        {
            if (subFogConfigMap.ContainsKey(currentFogId))
            {
                fogTexture.SetPixel(grid.x, grid.y, subFogConfigMap[currentFogId].color);
                // 写入数据中
                fogIdArray[grid.x, grid.y] = currentFogId;
            }
        }


        public void Save()
        {
#if UNITY_EDITOR

            if (!editing)
            {
                return;
            }
            
            // 创建一个配置 
            CityFogConfig cityFogConfig = new CityFogConfig();
            cityFogConfig.width = width;
            cityFogConfig.height = height;
            cityFogConfig.fogSize = fogSize;
            cityFogConfig.fogPosY = fogPosY;
            cityFogConfig.fogOffsetX = fogOffsetX;
            cityFogConfig.fogOffsetZ = fogOffsetZ;

            cityFogConfig.CitySubFogs = new List<CitySubFog>();

            Dictionary<int, CitySubFog> citySubFogMap = new Dictionary<int, CitySubFog>();

            for (int i = 0; i < fogIdArray.GetLength(0); i++)
            {
                for (int j = 0; j < fogIdArray.GetLength(1); j++)
                {
                    int fogId = fogIdArray[i, j];
                    if (fogId <= 0)
                    {
                        continue;
                    }
                    
                    if (!citySubFogMap.ContainsKey(fogId))
                    {
                        CitySubFog subFog = new CitySubFog();
                        subFog.fogId = fogId;
                        subFog.grids = new List<Vector2Int>();
                        citySubFogMap[fogId] = subFog;
                    }
                    
                    citySubFogMap[fogId].grids.Add(new Vector2Int(i,j));
                }
            }
            
            cityFogConfig.CitySubFogs.AddRange(citySubFogMap.Values);

            var jsonText = JsonUtility.ToJson(cityFogConfig,false);
            FileStream fs = new FileStream(fogJsonPath, FileMode.Create, FileAccess.Write);
            using (StreamWriter writer = new StreamWriter(fs))
            {
                writer.Write(jsonText);
                writer.Flush();
                writer.Close();
                fs.Close();
            }
            AssetDatabase.Refresh();
#endif

        }
        
        
        private void OnApplicationQuit()
        {
            //Save();
            End();
        }
    }
}